<template>
  <div class="search">
    <Card>
      <Row>
        <Form
          ref="editForm"
          :model="editForm"
          :rules="addRule"
          style="width: 100%"
          :label-width="120"
        >
          <FormItem label="基地所属单位" prop="deptId">
            <Select
              v-model="editForm.deptId"
              placeholder="请选择单位"
              clearable
              style="width: 40%"
            >
              <Option v-for="(item, k) in unitList" :key="k" :value="item.id">{{
                item.title
              }}</Option>
            </Select>
          </FormItem>
          <FormItem label="实践实训基地名称" prop="name">
            <Input
              v-model="editForm.name"
              placeholder="请输入实践实训基地名称"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="实践实训基地类型" prop="type">
            <Select
              v-model="editForm.type"
              placeholder="请选择基地类型"
              clearable
              style="width: 40%"
            >
              <Option v-for="(i, k) in typeList" :key="k" :value="i.id">{{
                i.name
              }}</Option>
            </Select>
            <Icon
              type="md-settings"
              :size="16"
              style="margin-left: 8px"
              @click="handleView"
            />
          </FormItem>
          <FormItem label="容纳人数" prop="capacity">
            <Input
              v-model="editForm.capacity"
              type="number"
              placeholder="请输入容纳人数"
              style="width: 40%"
            />
            <span style="margin-left: 10px">人</span>
          </FormItem>
          <FormItem label="基地地址" prop="siteAddress">
            <Input
              v-model="editForm.siteAddress"
              placeholder="请输入基地地址"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="基地电话" prop="telephone">
            <Input
              v-model="editForm.telephone"
              :maxlength="20"
              placeholder="请输入基地电话"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="收费标准" prop="isCharge">
            <RadioGroup v-model="editForm.isCharge">
              <Radio label="0">免费</Radio>
              <Radio label="1">收费</Radio>
            </RadioGroup>
            <Input
              v-if="editForm.isCharge == 1"
              v-model="editForm.unitPrice"
              type="number"
              style="width: 200px"
              placeholder="请输入金额"
            /><span v-if="editForm.isCharge == 1" style="margin-left: 10px">元/小时</span>
          </FormItem>
          <FormItem label="基地照片" prop="picList" style="width: 100%">
            <div
              class="baseItem"
              v-for="(i, k) in editForm.picList"
              :key="k"
              @mouseleave="i.hover = false"
              @mouseover="i.hover = true"
            >
              <img :src="i.src" />
              <Icon
                class="base-icon"
                @click="handleDelPic(k)"
                v-if="i.hover"
                type="md-trash"
              />
            </div>
            <Upload
              action
              type="drag"
              ref="upload"
              multiple
              v-if="editForm.picList.length < 4"
              :max-size="2 * 1024"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              accept=".jpg, .jpeg, .png"
              :format="['jpg', 'jpeg', 'png']"
              style="width: max-content; display: inline-block"
            >
              <div style="width: 150px; height: 150px; line-height: 150px">
                <Icon type="md-add" size="20" />
              </div>
            </Upload>
            <span
              style="margin-left: 20px; color: #aaa"
              v-if="editForm.picList.length < 4"
              >只能上传jpg/png文件，且不超过2MB</span
            >
          </FormItem>
          <FormItem label="实践实训基地介绍" prop="trainingBaseDetail">
            <Editor :richText.sync="editForm.trainingBaseDetail" :defaultText="defaultText" style="max-width: 800px" />
          </FormItem>
          <div>
            <Button type="text" @click="toback">返回</Button>
            <Button type="primary" @click="submitForm">提交</Button>
          </div>
        </Form>
      </Row>
    </Card>
    <Modal v-model="typeFlag" title="添加实践实训基地类型">
      <div v-for="(i, k) in typeList" :key="k" class="typeItem">
        <span>{{ i.name }}</span>
        <Icon type="ios-close-circle-outline" :size="16" @click="handleDelType(i)" />
      </div>
      <Form ref="typeForm" :model="typeForm" inline :rules="typeRule">
        <FormItem prop="name">
          <Input v-model="typeForm.name" placeholder="请输入实践实训基地类型" />
        </FormItem>
        <FormItem>
          <Button type="text" style="color: #409eff;" :loading="typeLoading" @click="submitType">添加</Button>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="typeFlag = false">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import * as API_Train from "@/api/trainbase.js";
import Editor from '@/components/editor/WEditor.vue';

export default {
  name: "base-form",
  components: {
    Editor,
  },
  data() {
    return {
      defaultText:"",
      loading: true, // 表单加载状态
      typeLoading: false, // 提交基地类型中
      editForm: {
        picList:[]
      }, // 表单
      unitList: [], // 所属单位
      typeList: [], // 基地类型
      addRule: {
        // 验证规则
        deptId: [{ required: true, message: "请输入基地所属单位" }],
        name: [{ required: true, message: "请输入实践实训基地名称" }],
        type: [{ required: true, message: "请选择实践实训基地类型" }],
        capacity: [{ required: true, message: "请输入容纳人数" }],
        siteAddress: [{ required: true, message: "请输入基地地址" }],
        telephone: [
          { required: true, message: "请输入基地电话" },
          { pattern: /^[0-9\-]+$/, message: "电话格式不正确" },
        ],
        isCharge: [{ required: true, message: "请选择收费标准" }],
        picList: [{ required: true, message: "请上传基地照片" }],
        remark: [{ required: true, message: "请输入基地介绍" }],
      },
      typeFlag: false, // 新增基地类型弹窗
      typeForm: {
        name: "", //类型名称
      },
      typeRule: {
        name: [
          { required: true, message: "请输入实践实训基地类型" },
          { max: 5, message: "最多五个字符" },
        ],
      },
    };
  },
  watch: {
    typeFlag(val) {
      if (val) this.$refs.typeForm.resetFields();
    },
  },
  mounted() {
    this.getBaseType();
    this.getBaseUnit();
    let id = this.$route.query.id;
    this.init(id);
  },
  methods: {
    // 返回上级
    toback() {
      this.$store.commit("removeTag", "base-form");
      this.$router.go(-1);
    },
    // 初始化表单
    init(id) {
      let form = {
        id: null,
        deptId: null, //基地所属单位
        name: null, //基地名称
        type: null, //基地类型
        capacity: null, //容纳人数
        siteAddress: null, //基地地址
        telephone: null, //基地电话
        isCharge: null, //是否收费 0免费，1收费
        unitPrice: null, //单价（元/小时）
        trainingBaseCover: null, //基地封面
        picUrls: null, // 基地图片集合
        picList: [], // 临时基地图片集合
        trainingBaseDetail: null, //基地详情介绍
      };
      if (id) {
        API_Train.getTrainBaseInfo(id).then((res) => {
          if (res.success) {
            this.editForm = Object.assign(form, res.result);
            let list = this.editForm.picUrls.split(",");
            this.editForm.picList = list.map((i) => {
              return { src: i, hover: false };
            });
            this.$nextTick(()=>{
             this.defaultText= this.editForm.trainingBaseDetail
            })
          }
        });
      } else {
        this.editForm = Object.assign({}, form);
      }
      this.$refs.editForm.resetFields();
    },
    // 自定义上传
    beforeUpload(file) {
      let typeList = [".jpg", ".jpeg", ".png"];
      if (!typeList.some((i) => file.name.lastIndexOf(i) != -1)) {
        this.$Message.warning("请检查上传文件格式");
        return;
      }
      if (file.size / 1024 > 2 * 1024) {
        this.$Message.warning("图片大小不能超过2MB");
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      API_Train.postUpload(formData).then((res) => {
        if (res.success) {
          let list = this.editForm.picList;
          if (list.length < 4) {
            this.editForm.picList.push({ src: res.result, hover: false });
            this.editForm.picUrls = this.editForm.picList
              .map((i) => {
                return i.src;
              })
              .join(",");
          }
          if (list.length) this.editForm.trainingBaseCover = list[0].src;
        }
      });
      return false;
    },
    // 添加实践实训基地类型
    handleView() {
      this.getBaseType();
      this.typeFlag = true;
    },
    // 删除图片
    handleDelPic(k) {
      this.editForm.picList.splice(k, 1);
    },
    // 删除基地类型
    handleDelType(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: `<p>确认删除基地类型【${v.name}】吗？</p>`,
        onOk: () => {
          API_Train.delTrainBaseType(v.id).then((res) => {
            if (res.success) {
              this.$Message.success("删除成功");
              this.getBaseType();
            }
          });
        },
      });
    },
    // 提交基地类型
    submitType() {
      this.$refs.typeForm.validate((valid) => {
        if (valid) {
          this.typeLoading = true;
          API_Train.postTrainBaseType(this.typeForm).then((res) => {
            if (res.success) {
              this.$Message.success("添加成功");
              this.$refs.typeForm.resetFields();
              this.getBaseType();
            }
          }).finally(()=>{
            this.typeLoading = false;
          })
        }
      });
    },
    //提交
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let params = Object.assign({}, this.editForm);
          if(params.trainingBaseDetail){
            let text = this.replaceHTML(params.trainingBaseDetail);
            if (text && text.length > 10000) {
              this.$Message.warning(`当前字数为${text.length}字，字数不能超过10000字`);
              return;
            }
          }
          if (params.isCharge == 0) params.unitPrice = null;
          delete params.picList;
          API_Train.postTrainBase(params).then((res) => {
            if (res.success) {
              this.$Message.success((params.id ? "修改" : "新增") + "成功");
              this.toback();
            }
          });
        }
      });
    },
    // 获取基地所属单位
    getBaseUnit() {
      API_Train.getTrainBaseUnit().then((res) => {
        if (res.success) {
          this.unitList = res.result;
        }
      });
    },
    // 获取实训基地类型
    getBaseType() {
      API_Train.getTrainBaseType().then((res) => {
        if (res.success) {
          this.typeList = res.result;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.tox.tox-tinymce.tox-fullscreen {
  top: 110px !important;
  left: 190px !important;
  width: calc(100% - 202px) !important;
  height: calc(100% - 122px) !important;
}
.baseItem {
  display: inline-block;
  position: relative;
  height: 150px;
  margin-right: 10px;
  .base-icon {
    position: absolute;
    top: 5px;
    color: #fff;
    font-size: 20px;
    right: 5px;
    &:hover {
      cursor: pointer;
    }
  }
  &:hover {
    opacity: 0.9;
  }
  img {
    height: 100%;
  }
}
.typeItem {
  user-select: none;
  display: inline-block;
  padding: 6px 15px;
  border-radius: 2px;
  color: #333333;
  border: 1px solid transparent;
  white-space: nowrap;
  background-color: #F0F2F5;
  margin: 10px 10px 10px 0;
  &:hover {
    cursor: pointer;
    border: 1px solid #ff605c;
  }
  span {
    margin-right: 10px;
  }
}
</style>
